<?php

class Smarty_mysql_resource extends Smarty_Resource_Custom {

	protected $pages_table = 'foria_pages';
	protected $templates_table = 'foria_templates';
	protected $db		= null;

	function __construct()
	{
		$this->ci = &get_instance();
		$this->db = &$this->ci->db;
		$this->template = '{main}';
		$this->data = array();
	}


	public function fetch($name, &$source, &$mtime)
	{
		if (!isset($this->data['modified']))
		{
			$this->data = $this->_by_name ($name);
		}
		if (isset($this->data['content']) && isset($this->data['modified']))
		{
			if (isset($this->data['tdata']['content'])) {
				$source = $this->data['tdata']['content'];
				$source = preg_replace ('/{main}/', $this->data['content'], $source);
			}
			else
			{
				$source = $this->data['content'];
			}
			$mtime =  $this->data['modified'];
			if (isset($this->data['tdata']['modified']) && $this->data['tdata']['modified']>$mtime)
				$mtime = $this->data['tdata']['modified'];
		} else {
			$source = null;
			$mtime = null;
		}
	}

	public function fetchTimestamp($name) {
		$this->data = $this->_by_name ($name);
		if (isset($this->data['modified']))
		{
			$mtime = $this->data['modified'];
			if (isset($this->data['tdata']['modified']) && $this->data['tdata']['modified']>$mtime)
				$mtime = $this->data['tdata']['modified'];
		} else {
			$mtime = null;
		}
		return $mtime;
	}

	public function _by_name ($name = "")
	{
		$type = "";
		$parent_id = 0;
		if (strpos($name, '#')>0)
		{
			list($type, $name) = explode ('#', $name);
		}
		$names = explode ('/', $name);
		$data = array ();
		if ($type=='page')
		{
			$table  = $this->pages_table;
			$fields = 'id, parent_id, id, name, content, template, modified';
		} else {
			$table  = $this->templates_table;
			$fields = 'id, parent_id, name, content, modified';
		}
		foreach ($names as $n)
		{
			$this->db->where('parent_id', $parent_id);
			$this->db->where('name', $n);
			$this->db->select($fields);
			$query = $this->db->get($table);
			if ($row = $query->result_array())
			{
				$data = $row[0];
				$parent_id = $row[0]['id'];
			}
		}
		if ($type == "page")
		{
			$data['tdata'] = $this->_by_name ($data['template']);
		}
		return $data;
	}

}